package fun.ticsmyc.dataStructure;

/**
 * @author Ticsmyc
 * @package fun.ticsmyc.dataStructure
 * @date 2020-02-13 12:40
 */

import org.junit.Test;

import java.util.Arrays;

/**
 * 栈
 */
class MyStack{

    private final int[] num;
    private int top;

    public MyStack(int size){
        num = new int[size];
        top =-1;
    }

    public boolean push(int number){
        if(top == num.length-1){
            return false;
        }
        num[++top]=number;
        return true;
    }
    public int pop(){
        if(top>-1){
            return num[top--];
        }else{
            return 0;
        }
    }
    public boolean isEmpty(){
        return top == -1;
    }
}

/**
 * 队列
 */
class MyQueue{
    private final int[] nums;

    /**
     * 队首
     */
    private int head;
    /**
     * 队尾
     */
    private int tail;
    /**
     * 队中元素个数
     */
    private int size;

    public MyQueue(int length) {
        nums = new int[length];
        head = 0;
        tail = -1;
        size = 0;
    }

    /**
     * 入队列
     * @param number
     */
    public boolean EnQueue(int number){
        if(size ==nums.length){
            return false;
        }
        nums[ (++tail)%nums.length ] = number;
        size++;
        return true;
    }

    /**
     * 出队列
     * @return
     */
    public int DeQueue(){
        if(size ==0){
            return 0;
        }
        int res =nums[head];
        head = (head+1)%nums.length;
        size--;
        return res;
    }

    public String print(){
        return Arrays.toString(nums);
    }

}

public class 数组实现栈and队列 {
    @Test
    public void testStack(){
        MyStack stack = new MyStack(2);
        System.out.println(stack.push(1));
        System.out.println(stack.push(2));
        System.out.println(stack.push(3));
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }

    @Test
    public void testQueue(){
        MyQueue queue = new MyQueue(3);
        System.out.println("出: "+queue.DeQueue()+"  "+queue.print());
        System.out.println("入： "+queue.EnQueue(1)+"  "+queue.print());
        System.out.println("入： "+queue.EnQueue(2)+"  "+queue.print());
        System.out.println("出: "+queue.DeQueue()+"  "+queue.print());
        System.out.println("入： "+queue.EnQueue(3)+"  "+queue.print());
        System.out.println("入： "+queue.EnQueue(4)+"  "+queue.print());
        System.out.println("出: "+queue.DeQueue()+"  "+queue.print());
        System.out.println("出: "+queue.DeQueue()+"  "+queue.print());
        System.out.println("出: "+queue.DeQueue()+"  "+queue.print());
        System.out.println("出: "+queue.DeQueue()+"  "+queue.print());
    }
}
